<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use Exception;

/**
 * 员工报工前台控制器
 */
class Worker extends Frontend
{
    protected $noNeedRight = ['*'];
    protected $noNeedLogin = ['test']; // 只有test方法不需要登录

    public function _initialize()
    {
        parent::_initialize();
        $this->view->assign('title', '员工报工系统');
    }
    
    /**
     * 测试方法
     */
    public function test()
    {
        $this->success('Worker控制器工作正常', null, ['worker_id' => $this->auth->id]);
    }

    /**
     * 员工首页
     */
    public function index()
    {
        // 检查是否已登录
        if (!$this->auth->isLogin()) {
            // 未登录，重定向到登录页面
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        // 获取员工信息
        $worker = $this->auth->getUser();
        $this->view->assign('worker', $worker);

        // ====== 新增首页统计数据 ======
        $userId = $this->auth->id;
        $today = date('Y-m-d');
        $startTime = strtotime($today . ' 00:00:00');
        $endTime = strtotime($today . ' 23:59:59');
        // 今日任务数（今日新分配）
        $todayTaskCount = Db::name('scanwork_allocation')
            ->where('user_id', $userId)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->count();
        // 今日报工数（已确认）
        $todayReportCount = Db::name('scanwork_report')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('quantity');
        // 今日工资（已确认）
        $todayWage = Db::name('scanwork_report')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('wage');
        $this->view->assign([
            'todayTaskCount' => $todayTaskCount,
            'todayReportCount' => $todayReportCount,
            'todayWage' => $todayWage ?: 0,
        ]);
        // ====== END ======
        return $this->view->fetch('worker/index');
    }

    /**
     * 我的任务页面（只渲染视图）
     */
    public function tasks()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        $workerId = $this->auth->id;
        $tasks = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.user_id', $workerId)
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('a.createtime desc')
            ->select();
        // 计算已报数量和待报数量
        foreach ($tasks as &$task) {
            $reportedQuantity = Db::name('scanwork_report')
                ->where('allocation_id', $task['id'])
                ->where('status', 1)
                ->sum('quantity');
            $task['reported_quantity'] = intval($reportedQuantity);
            $task['remaining_quantity'] = max(0, $task['quantity'] - $task['reported_quantity']);
        }
        $this->view->assign('tasks', $tasks);
        return $this->view->fetch('worker/tasks');
    }

    /**
     * 任务数据接口（AJAX专用）
     */
    public function tasksData()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录', null, ['code' => 401]);
        }
        try {
            $workerId = $this->auth->id;
            $allocations = Db::name('scanwork_allocation')
                ->where('user_id', $workerId)
                ->where('status', 0)
                ->order('createtime desc')
                ->select();
            $this->success('', null, $allocations);
        } catch (Exception $e) {
            $this->error('获取任务列表失败：' . $e->getMessage() . ' | ' . $e->getFile() . ':' . $e->getLine());
        }
    }
    /**
     * 报工页面
     */
    public function report()
    {
        // 兼容 GET 参数和 pathinfo 方式获取 allocation_id
        $allocationId = $this->request->param('id') ?: $this->request->post('allocation_id');
        
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        
        if (!$allocationId) {
            $this->error('未指定任务ID，无法报工');
        }
        
        $workerId = $this->auth->id;
        $error = '';
        $success = '';
        
        // 获取可报工的产品编号
        $productItems = [];
        if ($allocationId) {
            $productItems = Db::name('scanwork_product_item')
                ->where('allocation_id', $allocationId)
                ->where('status', 0) // 未报工状态
                ->order('item_no')
                ->select();
        }
        
        if ($this->request->isPost()) {
            try {
                $allocationId = $this->request->post('allocation_id');
                
                // 处理产品编号数组
                $itemNos = [];
                $postData = $this->request->post();
                if (isset($postData['item_nos']) && is_array($postData['item_nos'])) {
                    $itemNos = $postData['item_nos'];
                }
                
                $remark = $this->request->post('remark');
                $workType = $this->request->post('work_type', 'piece');
                
                // 基本验证
                if (!$allocationId) {
                    $error = '参数错误: allocation_id=' . var_export($allocationId,true);
                } else {
                    // 获取分配记录
                    $allocation = Db::name('scanwork_allocation')
                        ->alias('a')
                        ->join('scanwork_order o', 'a.order_id = o.id')
                        ->join('scanwork_model m', 'a.model_id = m.id')
                        ->join('scanwork_product p', 'm.product_id = p.id')
                        ->join('scanwork_process pr', 'a.process_id = pr.id')
                        ->where('a.id', $allocationId)
                        ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
                        ->find();
                    
                    if (!$allocation) {
                        $error = '分工不存在: allocation_id=' . var_export($allocationId,true);
                    } else {
                        // 计算数量
                        if ($workType == 'piece') {
                            $quantity = count($itemNos);
                            if ($quantity <= 0) {
                                $error = '请选择要报工的产品编号';
                            }
                        } else {
                            $quantity = intval($this->request->post('work_hours', 0));
                            if ($quantity <= 0) {
                                $error = '请输入工时';
                            }
                        }
                        
                        if (!$error) {
                            try {
                                Db::startTrans();
                                
                                // 创建报工记录
                                $reportData = [
                                    'allocation_id' => $allocationId,
                                    'user_id' => $workerId,
                                    'quantity' => $quantity,
                                    'remark' => $remark,
                                    'status' => 0, // 待审核
                                    'wage' => 0, // 待计算
                                    'createtime' => time(),
                                    'updatetime' => time()
                                ];
                                
                                // 如果是计件工作，添加产品编号
                                if ($workType == 'piece' && !empty($itemNos)) {
                                    $reportData['item_nos'] = json_encode($itemNos);
                                }
                                
                                $reportId = Db::name('scanwork_report')->insertGetId($reportData);
                                
                                // 更新产品编号状态
                                if ($workType == 'piece' && !empty($itemNos)) {
                                    foreach ($itemNos as $itemNo) {
                                        Db::name('scanwork_product_item')
                                            ->where('item_no', $itemNo)
                                            ->update([
                                                'status' => 1, // 已报工
                                                'report_id' => $reportId,
                                                'updatetime' => time()
                                            ]);
                                    }
                                }
                                
                                // 处理图片上传
                                if ($workType == 'piece' && !empty($itemNos)) {
                                    // 计件工作：处理每个产品编号的图片
                                    $cloudService = new \app\common\service\ScanworkCloudService();
                                    
                                    // 处理每个产品编号的图片
                                    error_log("开始处理图片上传，FILES结构: " . print_r($_FILES, true));
                                    if (!empty($_FILES['item_images']) && is_array($_FILES['item_images']['name'])) {
                                        foreach ($_FILES['item_images']['name'] as $itemNo => $files) {
                                            // 检查该产品编号是否在选中的列表中
                                            if (!in_array($itemNo, $itemNos)) continue;
                                            
                                            $item = Db::name('scanwork_product_item')->where('item_no', $itemNo)->find();
                                            if (!$item) continue;
                                            
                                            $count = 0;
                                            error_log("处理产品编号 $itemNo 的图片，文件数量: " . count($files));
                                            if (is_array($files)) {
                                                foreach ($files as $k => $filename) {
                                                    error_log("处理文件 $k: $filename");
                                                    if (!isset($_FILES['item_images']['error'][$itemNo][$k]) || 
                                                        $_FILES['item_images']['error'][$itemNo][$k] != 0) {
                                                        continue;
                                                    }
                                                    
                                                    if ($count >= 9) break;
                                                    
                                                    // 构建文件数组
                                                    $file = [
                                                        'name' => $_FILES['item_images']['name'][$itemNo][$k],
                                                        'type' => $_FILES['item_images']['type'][$itemNo][$k],
                                                        'tmp_name' => $_FILES['item_images']['tmp_name'][$itemNo][$k],
                                                        'error' => $_FILES['item_images']['error'][$itemNo][$k],
                                                        'size' => $_FILES['item_images']['size'][$itemNo][$k]
                                                    ];
                                                    
                                                    // 上传到云存储
                                                    $result = $cloudService->uploadReportImage($file);
                                                    
                                                    if ($result['success']) {
                                                        // 保存到产品报工图片表
                                                        Db::name('scanwork_item_report_image')->insert([
                                                            'item_id' => $item['id'],
                                                            'report_id' => $reportId,
                                                            'image_url' => $result['url'],
                                                            'cloud_file_id' => $result['file_id'],
                                                            'upload_user_id' => $workerId,
                                                            'createtime' => time()
                                                        ]);
                                                        $count++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    // 计时工作：处理普通图片上传
                                    if (!empty($_FILES['images']) && is_array($_FILES['images']['tmp_name'])) {
                                        $cloudService = new \app\common\service\ScanworkCloudService();
                                        $count = 0;
                                        foreach ($_FILES['images']['tmp_name'] as $k => $tmp) {
                                            if ($_FILES['images']['error'][$k] == 0) {
                                                if ($count >= 9) break;
                                                
                                                // 构建文件数组
                                                $file = [
                                                    'name' => $_FILES['images']['name'][$k],
                                                    'type' => $_FILES['images']['type'][$k],
                                                    'tmp_name' => $_FILES['images']['tmp_name'][$k],
                                                    'error' => $_FILES['images']['error'][$k],
                                                    'size' => $_FILES['images']['size'][$k]
                                                ];
                                                
                                                // 上传到云存储
                                                $result = $cloudService->uploadReportImage($file);
                                                
                                                if ($result['success']) {
                                                    // 保存到普通报工图片表
                                                    Db::name('scanwork_report_image')->insert([
                                                        'report_id' => $reportId,
                                                        'image_url' => $result['url'],
                                                        'cloud_file_id' => $result['file_id'],
                                                        'createtime' => time()
                                                    ]);
                                                    $count++;
                                                }
                                            }
                                        }
                                    }
                                }
                                
                                // 立即增加分工表的已报数量
                                Db::name('scanwork_allocation')->where('id', $allocationId)->setInc('reported_quantity', $quantity);
                                
                                Db::commit();
                                $success = '报工提交成功，等待审核确认';
                                $error = '';
                                
                            } catch (\Exception $e) {
                                Db::rollback();
                                error_log("数据库操作异常: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
                                $error = '数据库操作异常: ' . $e->getMessage();
                                $success = '';
                            }
                        }
                    }
                }
                
            } catch (\Exception $e) {
                error_log("数据接收异常: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine());
                $error = '数据接收异常: ' . $e->getMessage();
                $success = '';
            }
        }
        
        // 回显任务信息
        if ($allocationId) {
            $allocation = Db::name('scanwork_allocation')
                ->alias('a')
                ->join('scanwork_order o', 'a.order_id = o.id')
                ->join('scanwork_model m', 'a.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->join('scanwork_process pr', 'a.process_id = pr.id')
                ->where('a.id', $allocationId)
                ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
                ->find();
            if ($allocation) {
                $reportedQuantity = Db::name('scanwork_report')
                    ->where('allocation_id', $allocation['id'])
                    ->where('status', 1)
                    ->sum('quantity');
                $pendingQuantity = Db::name('scanwork_report')
                    ->where('allocation_id', $allocation['id'])
                    ->where('status', 0)
                    ->sum('quantity');
                $allocation['reported_quantity'] = intval($reportedQuantity) + intval($pendingQuantity);
                $allocation['remaining_quantity'] = max(0, $allocation['quantity'] - $allocation['reported_quantity']);
                $this->view->assign('allocation', $allocation);
            }
        }
        
        $this->view->assign('error', $error);
        $this->view->assign('success', $success);
        $this->view->assign('productItems', $productItems);
        return $this->view->fetch('worker/report');
    }


    /**
     * 提交报工（支持多图上传）
     */
    public function submit()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        $workerId = $this->auth->id;
        if ($this->request->isPost()) {
            $allocationId = $this->request->post('allocation_id');
            $quantity = intval($this->request->post('quantity'));
            if (!$allocationId || $quantity <= 0) {
                $this->error('参数错误: allocation_id=' . var_export($allocationId,true) . ', quantity=' . var_export($quantity,true));
            }
            // 验证分配记录
            $allocation = Db::name('scanwork_allocation')->where('id', $allocationId)->where('user_id', $workerId)->find();
            if (!$allocation) {
                $this->error('无权操作此任务: allocation_id=' . var_export($allocationId,true) . ', user_id=' . var_export($workerId,true));
            }
            // 计算剩余数量
            $reportedQuantity = Db::name('scanwork_report')
                ->where('allocation_id', $allocationId)
                ->where('status', 1)
                ->sum('quantity');
            $remainingQuantity = max(0, $allocation['quantity'] - $reportedQuantity);
            if ($quantity > $remainingQuantity) {
                $this->error('报工数量不能超过待报数量，已报：' . $reportedQuantity . '，分配：' . $allocation['quantity'] . '，本次报工：' . $quantity);
            }
            Db::startTrans();
            try {
                // 创建报工记录
                $reportId = Db::name('scanwork_report')->insertGetId([
                    'allocation_id' => $allocationId,
                    'user_id' => $workerId,
                    'quantity' => $quantity,
                    'status' => 0, // 待审核
                    'wage' => 0, // 待计算
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                // 多图上传处理
                if (!empty($_FILES['images']) && is_array($_FILES['images']['tmp_name'])) {
                    $cloudService = new \app\common\service\ScanworkCloudService();
                    $count = 0;
                    foreach ($_FILES['images']['tmp_name'] as $k => $tmp) {
                        if ($_FILES['images']['error'][$k] == 0) {
                            if ($count >= 9) break;
                            
                            // 构建文件数组
                            $file = [
                                'name' => $_FILES['images']['name'][$k],
                                'type' => $_FILES['images']['type'][$k],
                                'tmp_name' => $_FILES['images']['tmp_name'][$k],
                                'error' => $_FILES['images']['error'][$k],
                                'size' => $_FILES['images']['size'][$k]
                            ];
                            
                            // 上传到云存储
                            $result = $cloudService->uploadReportImage($file);
                            
                            if ($result['success']) {
                                Db::name('scanwork_report_image')->insert([
                                    'report_id' => $reportId,
                                    'image_url' => $result['url'],
                                    'cloud_file_id' => $result['file_id'],
                                    'createtime' => time()
                                ]);
                                $count++;
                            }
                        }
                    }
                }
                Db::commit();
                $this->success('报工提交成功，等待审核确认');
            } catch (Exception $e) {
                file_put_contents('/tmp/report_error.log', date('Y-m-d H:i:s') . ' ' . $e->getMessage() . ' | ' . $e->getFile() . ':' . $e->getLine() . PHP_EOL, FILE_APPEND);
                Db::rollback();
                $this->error('异常: ' . $e->getMessage() . ' | ' . $e->getFile() . ':' . $e->getLine());
            }
        }
        $this->error('请求方式错误: method=' . $this->request->method());
    }

    /**
     * 扫码报工
     */
    public function scan()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $workerId = $this->auth->id;
        \think\Log::info("scan方法被调用 - workerId: {$workerId}");
        
        // 检查是否有通过URL参数传递的allocation_id（来自二维码扫描）
        $allocationId = $this->request->get('allocation_id');
        \think\Log::info("scan方法 - allocationId: " . ($allocationId ?: 'null'));
        
        if ($allocationId) {
            // 直接处理二维码扫描的情况
            $this->processAllocationScan($allocationId, $workerId);
            return;
        }
        
        if ($this->request->isPost()) {
            $qrCode = $this->request->post('qr_code');
            
            if (!$qrCode) {
                $this->error('二维码数据不能为空');
            }
            
            // 解析二维码数据（格式：allocation_id）
            $allocationId = $qrCode;
            
        // 验证分配记录
        \think\Log::info("开始查询分配记录详情");
        try {
            $allocation = Db::name('scanwork_allocation')
                ->alias('a')
                ->join('scanwork_order o', 'a.order_id = o.id')
                ->join('scanwork_model m', 'a.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->join('scanwork_process pr', 'a.process_id = pr.id')
                ->where('a.id', $allocationId)
                ->where('a.user_id', $workerId)
                ->where('a.status', 0)
                ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
                ->find();
            \think\Log::info("分配记录查询结果: " . ($allocation ? '找到记录' : '未找到记录'));
        } catch (\Exception $e) {
            \think\Log::error("分配记录查询异常: " . $e->getMessage());
            $this->error('查询分配记录失败：' . $e->getMessage());
        }
            
            if (!$allocation) {
                $this->error('无效的二维码或任务已完成');
            }
            
            // 计算剩余数量
            $reportedQuantity = Db::name('scanwork_report')
                ->where('allocation_id', $allocationId)
                ->where('status', 1)
                ->sum('quantity');
            
            $remainingQuantity = max(0, $allocation['quantity'] - $reportedQuantity);
            
            if ($remainingQuantity <= 0) {
                $this->error('该任务已无待报数量');
            }
            
            $allocation['remaining_quantity'] = $remainingQuantity;
            $this->success('', null, $allocation);
        }
        
        return $this->view->fetch('worker/scan');
    }
    
    /**
     * 处理二维码扫描的分工分配
     */
    private function processAllocationScan($allocationId, $workerId)
    {
        // 添加调试信息
        \think\Log::info("processAllocationScan - allocationId: {$allocationId}, workerId: {$workerId}");
        
        // 先检查分配记录是否存在
        $allocationExists = Db::name('scanwork_allocation')->where('id', $allocationId)->find();
        if (!$allocationExists) {
            \think\Log::error("分配记录不存在 - allocationId: {$allocationId}");
            $this->error('分配记录不存在');
        }
        
        \think\Log::info("分配记录存在 - user_id: {$allocationExists['user_id']}, status: {$allocationExists['status']}");
        
        // 验证分配记录
        \think\Log::info("开始查询分配记录详情");
        $allocation = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.id', $allocationId)
            ->where('a.user_id', $workerId)
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
        
        \think\Log::info("分配记录查询结果: " . ($allocation ? '找到记录' : '未找到记录'));
        
        if (!$allocation) {
            \think\Log::error("分配记录验证失败 - allocationId: {$allocationId}, workerId: {$workerId}");
            $this->error('无效的二维码或任务已完成');
        }
        
        // 计算剩余数量
        $reportedQuantity = Db::name('scanwork_report')
            ->where('allocation_id', $allocationId)
            ->where('status', 1)
            ->sum('quantity');
        
        $remainingQuantity = max(0, $allocation['quantity'] - $reportedQuantity);
        
        if ($remainingQuantity <= 0) {
            $this->error('该任务已无待报数量');
        }
        
        $allocation['remaining_quantity'] = $remainingQuantity;
        
        // 直接重定向到报工页面
        $this->redirect('/index/worker/report/id/' . $allocationId);
    }

    /**
     * 我的报工记录
     */
    public function records()
    {
        if (!$this->auth->isLogin()) {
            if ($this->request->isAjax()) {
                $this->error('请先登录', null, ['code' => 401]);
            } else {
                $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
            }
        }
        
        try {
            $workerId = $this->auth->id;
            
            if ($this->request->isAjax()) {
                $page = $this->request->get('page', 1);
                $limit = $this->request->get('limit', 10);
                
                $reports = Db::name('scanwork_report')
                    ->alias('r')
                    ->join('scanwork_allocation a', 'r.allocation_id = a.id')
                    ->join('scanwork_order o', 'a.order_id = o.id')
                    ->join('scanwork_model m', 'a.model_id = m.id')
                    ->join('scanwork_product p', 'm.product_id = p.id')
                    ->join('scanwork_process pr', 'a.process_id = pr.id')
                    ->where('r.user_id', $workerId)
                    ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name, a.model_id, a.process_id')
                    ->order('r.createtime desc')
                    ->page($page, $limit)
                    ->select();
                
                $total = Db::name('scanwork_report')->where('user_id', $workerId)->count();
                
                $this->success('', null, [
                    'list' => $reports,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ]);
            }
            
            // 获取报工记录数据
            $reports = Db::name('scanwork_report')
                ->alias('r')
                ->join('scanwork_allocation a', 'r.allocation_id = a.id')
                ->join('scanwork_order o', 'a.order_id = o.id')
                ->join('scanwork_model m', 'a.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->join('scanwork_process pr', 'a.process_id = pr.id')
                ->where('r.user_id', $workerId)
                ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name, a.model_id, a.process_id')
                ->order('r.createtime desc')
                ->select();
            // 计算工价和工资金额，并查图片
            foreach ($reports as &$report) {
                $price = Db::name('scanwork_process_price')->where([
                    'model_id' => $report['model_id'],
                    'process_id' => $report['process_id']
                ])->value('price');
                $report['price'] = $price ? floatval($price) : 0;
                // 只有已确认才显示工资金额，否则为0
                if ($report['status'] == 1) {
                    $report['wage'] = round($report['price'] * $report['quantity'], 2);
                } else {
                    $report['wage'] = 0;
                }
                // 查图片
                $report['images'] = Db::name('scanwork_report_image')->where('report_id', $report['id'])->select();
            }
            $this->view->assign([
                'reports' => $reports
            ]);
            return $this->view->fetch('worker/records');
        } catch (Exception $e) {
            $this->error('获取报工记录失败：' . $e->getMessage());
        }
    }

    /**
     * 工资统计
     */
    public function wage()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        
        try {
            $workerId = $this->auth->id;
            
            if ($this->request->isAjax()) {
                $startDate = $this->request->get('start_date', date('Y-m-01'));
                $endDate = $this->request->get('end_date', date('Y-m-d'));
                
                $reports = Db::name('scanwork_report')
                    ->alias('r')
                    ->join('scanwork_allocation a', 'r.allocation_id = a.id')
                    ->join('scanwork_order o', 'a.order_id = o.id')
                    ->join('scanwork_model m', 'a.model_id = m.id')
                    ->join('scanwork_product p', 'm.product_id = p.id')
                    ->join('scanwork_process pr', 'a.process_id = pr.id')
                    ->where('r.user_id', $workerId)
                    ->where('r.status', 1)
                    ->where('r.createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')])
                    ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
                    ->order('r.createtime desc')
                    ->select();
                
                $totalQuantity = 0;
                $totalWage = 0;
                
                foreach ($reports as $report) {
                    $totalQuantity += $report['quantity'];
                    $totalWage += $report['wage'];
                }
                
                $this->success('', null, [
                    'reports' => $reports,
                    'total_quantity' => $totalQuantity,
                    'total_wage' => $totalWage
                ]);
            }
            
            // 获取默认日期范围的数据
            $startDate = $this->request->get('start_date', date('Y-m-01'));
            $endDate = $this->request->get('end_date', date('Y-m-d'));
            
            $reports = Db::name('scanwork_report')
                ->alias('r')
                ->join('scanwork_allocation a', 'r.allocation_id = a.id')
                ->join('scanwork_order o', 'a.order_id = o.id')
                ->join('scanwork_model m', 'a.model_id = m.id')
                ->join('scanwork_product p', 'm.product_id = p.id')
                ->join('scanwork_process pr', 'a.process_id = pr.id')
                ->where('r.user_id', $workerId)
                ->where('r.status', 1)
                ->where('r.createtime', 'between', [strtotime($startDate), strtotime($endDate . ' 23:59:59')])
                ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
                ->order('r.createtime desc')
                ->select();
            
            $totalQuantity = 0;
            $totalWage = 0;
            $confirmedWage = 0;
            $pendingWage = 0;
            
            foreach ($reports as $report) {
                $totalQuantity += $report['quantity'];
                $totalWage += $report['wage'];
                if ($report['status'] == 1) {
                    $confirmedWage += $report['wage'];
                } else {
                    $pendingWage += $report['wage'];
                }
            }
            
            $this->view->assign([
                'reports' => $reports,
                'total_quantity' => $totalQuantity,
                'total_wage' => $totalWage,
                'confirmed_wage' => $confirmedWage,
                'pending_wage' => $pendingWage,
                'start_date' => $startDate,
                'end_date' => $endDate
            ]);
            
            return $this->view->fetch('worker/wage');
        } catch (Exception $e) {
            $this->error('工资统计出错：' . $e->getMessage());
        }
    }
    
    /**
     * 统计图表数据
     */
    public function stats()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $workerId = $this->auth->id;
        
        // 获取最近7天的数据
        $dates = [];
        $quantities = [];
        
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $dates[] = $date;
            
            $quantity = Db::name('scanwork_report')
                ->where('user_id', $workerId)
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($date), strtotime($date . ' 23:59:59')])
                ->sum('quantity');
            
            $quantities[] = intval($quantity);
        }
        
        $this->success('', null, [
            'dates' => $dates,
            'quantities' => $quantities
        ]);
    }
    
    /**
     * 工资图表数据
     */
    public function wageChart()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $workerId = $this->auth->id;
        
        // 获取最近7天的工资数据
        $dates = [];
        $wages = [];
        
        for ($i = 6; $i >= 0; $i--) {
            $date = date('Y-m-d', strtotime("-{$i} days"));
            $dates[] = $date;
            
            $wage = Db::name('scanwork_report')
                ->where('user_id', $workerId)
                ->where('status', 1)
                ->where('createtime', 'between', [strtotime($date), strtotime($date . ' 23:59:59')])
                ->sum('wage');
            
            $wages[] = floatval($wage);
        }
        
        $this->success('', null, [
            'dates' => $dates,
            'wages' => $wages
        ]);
    }
    
    /**
     * 日报工数据
     */
    public function dailyReport()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $workerId = $this->auth->id;
        $date = $this->request->get('date', date('Y-m-d'));
        
        $reports = Db::name('scanwork_report')
            ->alias('r')
            ->join('scanwork_allocation a', 'r.allocation_id = a.id')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('r.user_id', $workerId)
            ->where('r.status', 1)
            ->where('r.createtime', 'between', [strtotime($date), strtotime($date . ' 23:59:59')])
            ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('r.createtime desc')
            ->select();
        
        $totalQuantity = 0;
        $totalWage = 0;
        
        foreach ($reports as $report) {
            $totalQuantity += $report['quantity'];
            $totalWage += $report['wage'];
        }
        
        $this->success('', null, [
            'reports' => $reports,
            'total_quantity' => $totalQuantity,
            'total_wage' => $totalWage,
            'date' => $date
        ]);
    }
    
   
    /**
     * 我的计时分工任务列表
     */
    public function ttasks()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        $workerId = $this->auth->id;
        $tasks = Db::name('scanwork_tallocationtime')
            ->where('user_id', $workerId)
            ->where('status', 0)
            ->order('work_date desc')
            ->select();
        $this->view->assign('tasks', $tasks);
        return $this->view->fetch('worker/ttasks');
    }

    /**
     * 计时报工页面
     */
    public function treport()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        $workerId = $this->auth->id;
        $taskId = $this->request->param('id');
        $error = '';
        $success = '';
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $tallocationtime_id = $params['tallocationtime_id'];
            $work_date = $params['work_date'];
            $start_time = $params['start_time'];
            $end_time = $params['end_time'];
            $total_hours = $params['total_hours'];
            $remark = $params['remark'];
            if (
                !$tallocationtime_id || !$work_date || !$total_hours
            ) {
                $error = '参数不完整';
            } else {
                // 查找分工任务
                $tallocation = Db::name('scanwork_tallocationtime')->where('id', $tallocationtime_id)->find();
                if (!$tallocation) {
                    $error = '分工任务不存在';
                } else {
                    // 查找工序工时单价
                    $processPrice = Db::name('scanwork_process_price')->where([
                        'model_id' => $tallocation['model_id'],
                        'process_id' => $tallocation['process_id']
                    ])->find();
                    if (!$processPrice) {
                        throw new \Exception('工序工价记录未找到，model_id=' . $tallocation['model_id'] . ', process_id=' . $tallocation['process_id']);
                    }                
                    $time_price = $processPrice ? floatval($processPrice['time_price']) : 0;
                    if ($time_price <= 0) {
                        $error = '工序工资未设置';
                    } else {
                        $wage = round($total_hours * $time_price, 2);
                        try {
                            Db::startTrans();
                            Db::name('scanwork_treporttime')->insert([
                                'tallocationtime_id' => $tallocationtime_id,
                                'user_id' => $workerId,
                                'work_date' => $work_date,
                                'start_time' => $start_time,
                                'end_time' => $end_time,
                                'total_hours' => $total_hours,
                                'wage' => $wage,
                                'remark' => $remark,
                                'status' => 0, // 待确认
                                'createtime' => time(),
                                'updatetime' => time()
                            ]);
                            Db::commit();
                            $success = '报工提交成功，等待审核';
                        } catch (Exception $e) {
                            Db::rollback();
                            $error = '异常: ' . $e->getMessage();
                        }
                    }
                }
            }
        }
        // 获取分工任务
        $tasks = Db::name('scanwork_tallocationtime')
            ->where('user_id', $workerId)
            ->where('status', 0)
            ->order('work_date desc')
            ->select();
        $this->view->assign('tasks', $tasks);
        $this->view->assign('error', $error);
        $this->view->assign('success', $success);
        return $this->view->fetch('worker/treport');
    }

    /**
     * 我的计时报工记录
     */
    public function trecords()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        $workerId = $this->auth->id;
        $records = Db::name('scanwork_treporttime')
            ->where('user_id', $workerId)
            ->order('work_date desc')
            ->select();
        $this->view->assign('records', $records);
        return $this->view->fetch('worker/trecords');
    }

    /**
     * 我的计时工资统计
     */
    public function twage()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        $workerId = $this->auth->id;
        $wages = Db::name('scanwork_twage')
            ->where('user_id', $workerId)
            ->order('work_date desc')
            ->select();
        $this->view->assign('wages', $wages);
        return $this->view->fetch('worker/twage');
    }

    /**
     * 删除报工图片
     */
    public function delete_report_image($id)
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        $img = Db::name('scanwork_report_image')->find($id);
        if (!$img) {
            $this->error('图片不存在');
        }
        $report = Db::name('scanwork_report')->where('id', $img['report_id'])->find();
        if (!$report || $report['user_id'] != $this->auth->id) {
            $this->error('无权操作');
        }
        if ($report['status'] != 0) {
            $this->error('已审核报工不能删除图片');
        }
        
        try {
            // 如果有云存储文件ID，删除云存储文件
            if (!empty($img['cloud_file_id'])) {
                $cloudService = new \app\common\service\ScanworkCloudService();
                $cloudService->deleteFile($img['cloud_file_id']);
            } else {
                // 删除本地文件
                @unlink(ROOT_PATH . 'public' . $img['image_url']);
            }
            
            Db::name('scanwork_report_image')->delete($id);
            $this->success('图片已删除');
        } catch (Exception $e) {
            $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 主动报工页面
     */
    public function activeReport()
    {
        if (!$this->auth->isLogin()) {
            $this->redirect('index/user/login?url=' . urlencode($this->request->url()));
        }
        
        $workerId = $this->auth->id;
        $error = '';
        $success = '';
        
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $order_id = $params['order_id'];
            $order_model = $params['order_model']; // 格式：model_id:process_id
            $report_type = $params['report_type']; // 'piece' 或 'time'
            $quantity = intval($params['quantity']);
            $work_hours = floatval($params['work_hours']);
            $start_time = $params['start_time'];
            $end_time = $params['end_time'];
            $work_date = $params['work_date'];
            $remark = $params['remark'];
            
            // 解析产品型号和工序ID
            $model_process = explode(':', $order_model);
            $model_id = $model_process[0];
            $process_id = $model_process[1];
            
            if (!$order_id || !$model_id || !$process_id || !$work_date) {
                $error = '请填写完整信息';
            } else {
                try {
                    Db::startTrans();
                    
                    // 验证订单是否存在
                    $order = Db::name('scanwork_order')->where('id', $order_id)->find();
                    if (!$order) {
                        throw new \Exception('订单不存在');
                    }
                    
                    // 验证产品型号是否存在
                    $model = Db::name('scanwork_model')->where('id', $model_id)->find();
                    if (!$model) {
                        throw new \Exception('产品型号不存在');
                    }
                    
                    // 验证工序是否存在
                    $process = Db::name('scanwork_process')->where('id', $process_id)->find();
                    if (!$process) {
                        throw new \Exception('工序不存在');
                    }
                    
                    // 查找工价
                    $processPrice = Db::name('scanwork_process_price')->where([
                        'model_id' => $model_id,
                        'process_id' => $process_id
                    ])->find();
                    
                    if (!$processPrice) {
                        throw new \Exception('该产品型号和工序的工价未设置');
                    }
                    
                    $wage = 0;
                    
                    if ($report_type == 'piece') {
                        // 计件报工
                        if ($quantity <= 0) {
                            throw new \Exception('计件数量必须大于0');
                        }
                        $wage = round($quantity * $processPrice['price'], 2);
                        
                        // 创建主动报工记录
                        $activeReportId = Db::name('scanwork_active_report')->insertGetId([
                            'order_id' => $order_id,
                            'model_id' => $model_id,
                            'process_id' => $process_id,
                            'report_type' => 'piece',
                            'quantity' => $quantity,
                            'wage' => $wage,
                            'work_date' => $work_date,
                            'remark' => $remark,
                            'user_id' => $workerId,
                            'status' => 0, // 待审核
                            'createtime' => time(),
                            'updatetime' => time()
                        ]);
                        
                    } else {
                        // 计时报工
                        $total_hours = $work_hours;
                        
                        // 如果填写了开始时间和结束时间，则计算工作时长
                        if (!empty($start_time) && !empty($end_time)) {
                            $start = strtotime($start_time);
                            $end = strtotime($end_time);
                            if ($start && $end && $end > $start) {
                                $total_hours = round(($end - $start) / 3600, 2);
                            } else {
                                throw new \Exception('开始时间必须早于结束时间');
                            }
                        } else if ($work_hours <= 0) {
                            throw new \Exception('请填写工作时长或开始结束时间');
                        }
                        
                        $wage = round($total_hours * $processPrice['time_price'], 2);
                        
                        // 创建主动报工记录
                        $activeReportId = Db::name('scanwork_active_report')->insertGetId([
                            'order_id' => $order_id,
                            'model_id' => $model_id,
                            'process_id' => $process_id,
                            'report_type' => 'time',
                            'work_hours' => $total_hours,
                            'start_time' => $start_time ?: '',
                            'end_time' => $end_time ?: '',
                            'wage' => $wage,
                            'work_date' => $work_date,
                            'remark' => $remark,
                            'user_id' => $workerId,
                            'status' => 0, // 待审核
                            'createtime' => time(),
                            'updatetime' => time()
                        ]);
                    }
                    
                    Db::commit();
                    $success = '主动报工提交成功，等待审核';
                    
                } catch (\Exception $e) {
                    Db::rollback();
                    $error = '提交失败：' . $e->getMessage();
                }
            }
        }
        
        // 获取订单列表 - 显示所有订单
        $orders = Db::name('scanwork_order')
            ->order('createtime desc')
            ->select();
            
        // 获取所有产品型号（用于显示）
        $models = Db::name('scanwork_model')
            ->alias('m')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->field('m.id, m.name, p.name as product_name')
            ->order('p.name, m.name')
            ->select();
            
        // 获取所有工序
        $processes = Db::name('scanwork_process')
            ->where('status', 1)
            ->order('name')
            ->select();
            
        $this->view->assign([
            'orders' => $orders,
            'models' => $models,
            'processes' => $processes,
            'error' => $error,
            'success' => $success
        ]);
        
        return $this->view->fetch('worker/active_report');
    }

    /**
     * 获取订单下的产品型号和工序
     */
    /**
     * 获取订单型号
     */
      /**
     * 获取订单型号
     */
    public function getOrderModels()
    {
        // 暂时移除登录检查，用于测试
        // if (!$this->auth->isLogin()) {
        //     $this->error('请先登录');
        // }
        
        $orderId = $this->request->get('order_id');
        if (!$orderId) {
            $this->error('参数错误');
        }

        $orderModels = \app\admin\model\scanwork\OrderModel::with(['model.product'])
            ->where('order_id', $orderId)
            ->select();

        // 获取所有工序
        $processes = Db::name('scanwork_process')
            ->where('status', 1)
            ->order('name')
            ->select();
            
        $result = [];
        foreach ($orderModels as $orderModel) {
            foreach ($processes as $process) {
                // 检查是否有该产品型号和工序的工价设置
                $processPrice = Db::name('scanwork_process_price')->where([
                    'model_id' => $orderModel->model_id,
                    'process_id' => $process['id']
                ])->find();
                
                if ($processPrice && $orderModel->model && $orderModel->model->product) {
                    $result[] = [
                        'model_id' => $orderModel->model_id,
                        'model_name' => $orderModel->model->name,
                        'product_name' => $orderModel->model->product->name,
                        'process_id' => $process['id'],
                        'process_name' => $process['name'],
                        'order_quantity' => $orderModel->quantity,
                        'piece_price' => $processPrice['price'],
                        'time_price' => $processPrice['time_price'],
                        'display_name' => $orderModel->model->product->name . ' - ' . $orderModel->model->name . ' (' . $process['name'] . ')'
                    ];
                }
            }
        }

        $this->success('获取成功', $result);
    }

    /**
     * 获取产品型号的工价信息
     */
    public function getProcessPrice()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $model_id = $this->request->get('model_id');
        $process_id = $this->request->get('process_id');
        
        if (!$model_id || !$process_id) {
            $this->error('参数错误');
        }
        
        $processPrice = Db::name('scanwork_process_price')->where([
            'model_id' => $model_id,
            'process_id' => $process_id
        ])->find();
        
        if (!$processPrice) {
            $this->error('该产品型号和工序的工价未设置');
        }
        
        $this->success('', null, [
            'price' => floatval($processPrice['price']),
            'time_price' => floatval($processPrice['time_price'])
        ]);
    }

    /**
     * 获取订单信息
     */
    public function getOrderInfo()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $order_id = $this->request->get('order_id');
        if (!$order_id) {
            $this->error('参数错误');
        }
        
        $order = Db::name('scanwork_order')->where('id', $order_id)->find();
        if (!$order) {
            $this->error('订单不存在');
        }
        
        // 计算已分配数量
        $allocatedQuantity = Db::name('scanwork_allocation')
            ->where('order_id', $order_id)
            ->sum('quantity');
        
        // 计算已报工数量
        $reportedQuantity = Db::name('scanwork_report')
            ->alias('r')
            ->join('scanwork_allocation a', 'r.allocation_id = a.id')
            ->where('a.order_id', $order_id)
            ->where('r.status', 1)
            ->sum('r.quantity');
        
        $this->success('', null, [
            'total_quantity' => $order['total_quantity'],
            'allocated_quantity' => $allocatedQuantity,
            'available_quantity' => max(0, $order['total_quantity'] - $allocatedQuantity - $reportedQuantity)
        ]);
    }
} 
